package elastic

import (
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/zeromicro/go-zero/core/logx"
	"go-zero-project/services/project/rpc/internal/config"
	"net/http"
	"time"
)

// InitClient 初始化elastic客户端
func InitClient(conf *config.ElasticSearchConf) (*elasticsearch.Client, error) {
	c := elasticsearch.Config{}
	c.Addresses = conf.Urls
	userName := conf.UserName
	if len(userName) > 0 {
		c.Username = conf.UserName
	}
	password := conf.Password
	if len(password) > 0 {
		c.Password = conf.Password
	}
	c.Transport = &http.Transport{
		MaxIdleConns:          conf.MaxConnectNum,
		IdleConnTimeout:       time.Second * time.Duration(conf.MaxConnectNum),
		ResponseHeaderTimeout: time.Second * time.Duration(conf.ResponseHeaderTimeout),
	}
	client, err := elasticsearch.NewClient(c)
	if err != nil {
		logx.Errorf("init elastic search failed,cause:%s ...", err.Error())
		return nil, err
	}
	logx.Infof("init elastic search success ...")
	return client, nil

}
